import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter);

import routes from './routes'

//处理NavigationDuplicated报错
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//通过加工这两个方法，如果没有传对应的回调函数，就补上一个回调函数
VueRouter.prototype.push = function(location, resolve, reject) {
    //此处this为VueRouter实例对象
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => {}, () => {});
    }
};
VueRouter.prototype.replace = function(location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => {}, () => {});
    }
};
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 };
    }
});
//全局路由守卫前置
router.beforeEach(async(to, from, next) => {
    //to即将跳转的路由，from来的路由的信息
    //next() 放行  next('/')放行到一个不同的地址，next(false)中断当前导航，返回from的地址
    //用户登录了才有token
    // next();
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name; //不能拿对象判断，要用对象里的值
    if (token) {
        //已经登陆的情况下想去login
        if (to.path == '/login') {
            next('/home');
        } else {
            //登陆，去的不是login【home|search|detail|shopcart】
            if (name) {
                next(); //如果用户名已有
            } else {
                //如果用户名没有，重发action获取
                try {
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    //token过期了 获取不到用户的信息
                    //清除所有的用户信息，重新登陆
                    await store.dispatch('logout');
                    next('/login');
                }
            }
        }
    } else {
        //未登录：不能去交易、支付相关【pay,paysuccess】、不能去个人中心【center】
        //上述页面跳到login
        //这些放行（home|search|shopcart）
        let toPath = to.path;
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            next('/login?redirect=' + toPath);
        } else {
            next();
        }
    }

});

export default router;